<template>
    <label class="pe-checkbox-button"
        :class="[modelValue1 || modelValue.includes(value) ? 'pe-checkbox-button-active' : '', checkboxDisabled1 || disabledArr.includes(value) ? 'pe-checkbox-button-disabled' : '', sizeArr.includes(checkboxSize) ? `pe-checkbox-button-${checkboxSize}` : '']">
        <input v-if="typeof modelValue1 !== 'boolean'" class="pe-checkbox-inp" type="checkbox" v-model="modelValue" :name="checkboxName1"
            @change="onChange" :value="value" :disabled="checkboxDisabled1 || disabledArr.includes(value)">
        <input v-else class="pe-checkbox-inp" type="checkbox" v-model="modelValue1" :disabled="checkboxDisabled1"
            @change="onChange1" :name="checkboxName1">
        <div class="pe-checkbox-button-content">
            <slot>{{ label }}</slot>
        </div>
    </label>
</template>

<script setup lang="ts">
import { Ref, inject, ref, watch, toRaw } from "vue"

const checkboxName: Ref<string> = inject("pe-checkbox-id", ref(""))
const modelValue: Ref<(string | number)[]> = inject("pe-checkbox-value", ref<(string | number)[]>([]))
const modelValue1 = defineModel<boolean>({ default: null })
const checkboxName1 = ref<string>("")

/**
 * @param value 选中状态的值（只有在checkbox-group或者绑定对象类型为array时有效）
 * @param label 选中状态的值，只有在绑定对象类型为 array 时有效。
 * @param disabled 是否禁用
 * @param name 原生 name 属性
 */
interface Props {
    value: string | number,
    label?: string | number,
    disabled?: boolean,
    name?: string
}

const props = withDefaults(defineProps<Props>(), {
    disabled: false
})

const checkboxSize = inject("pe-checkbox-size", ref<'default' | 'small' | 'large'>("default"))
const checkboxDisabled = inject("pe-checkbox-disabled", ref<boolean>(false))

const checkboxDisabled1 = ref<boolean>(false)

watch([props, checkboxDisabled], ([newProps, newDisabled]) => {
    checkboxName1.value = checkboxName.value
    if (newDisabled) {
        checkboxDisabled1.value = true
    } else {
        checkboxDisabled1.value = newProps.disabled
    }
    if (newProps.name) {
        checkboxName1.value = newProps.name
    }
}, { immediate: true })

const emits = defineEmits(["change"])

// 禁用多选框的value值
const disabledArr = inject("pe-checkbox-disabledArr", ref<(string | number)[]>([]))

// 绑定值改变时触发函数
const change = inject("pe-checkbox-change", Function, true)

const onChange = () => {
    change(toRaw(modelValue.value))
}

const onChange1 = (event: Event) => {
    const target: HTMLInputElement = event.target as HTMLInputElement
    emits("change", target.checked)
}

const sizeArr = ['small', 'large']
</script>

<script lang="ts">
export default {
    name: "pe-checkbox-button"
}
</script>